package com.example.service;

import cn.hutool.core.util.StrUtil;
import com.example.common.CustomerException;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {

    @Resource
    UserMapper userMapper;

    public String user(String user) {
        if (user.equals("user")) {
            return "user";
        } else {
            CustomerException customerException = new CustomerException();
            customerException.setMsg("账号或密码错误");
            customerException.setCode(500);
            throw customerException;
        }

    }

    public List<User> selectAll(User user) {
        return userMapper.selectAll(user);
    }

    public PageInfo<User> selectPage(Integer pageNum, Integer pageSize, User user) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.selectAll(user);
        return PageInfo.of(userList);
    }

    public void add(User user) {
        User resuser = userMapper.selectByUsername(user.getUsername());
        if  (resuser != null) {
            throw new CustomerException(501,"账号重复");
        }
        if (StrUtil.isBlank(user.getPassword())) {
            user.setPassword("123456");
        }
        user.setRole("USER");
        userMapper.insert(user);
    }

    public void update(User user) {
        userMapper.updateById(user);
    }

    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    public void deleteBatch(List<User> userList) {
        for (User user : userList) {
            this.deleteById(user.getId());
        }
    }

    public User login(Account account) {
        User dbuser = userMapper.selectByUsername(account.getUsername());
        if (dbuser == null) {
            throw new CustomerException(501,"账号不存在");
        }
        if (!account.getPassword().equals(dbuser.getPassword())) {
            throw new CustomerException(501,"账号或密码错误");
        }
        dbuser.setToken(TokenUtils.createToken(dbuser.getId()+"-USER",dbuser.getPassword()));

        return dbuser;
    }

    public void register(User user) {
        this.add(user);
    }

    public Account selectById(String id) {
        return userMapper.selectById(id);
    }

    public void updatePassword(Account account) {
        User dbuser = userMapper.selectById(account.getId().toString());
        dbuser.setPassword(account.getPassword());
        userMapper.updateById(dbuser);
    }
}
